#include"List.h"

ListNode* ListCreate(LTDataType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	node->prev = NULL;
	node->next = NULL;
	node->data = x;
	return node;
}
ListNode*  InitList()
{
	ListNode* phead = ListCreate(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}
void ListPrint(ListNode* plist)
{
	assert(plist);
	printf("phead<=>");
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
}
void ListPushBack(ListNode* plist, LTDataType x)
{
	assert(plist);
	ListNode* tail = plist->prev;
	ListNode* newnode = ListCreate(x);
	newnode->prev = tail;
	tail->next = newnode;
	newnode->next = plist;
	plist->prev = newnode;
}
void Popback(ListNode* plist)
{
	assert(plist);
	assert(plist->next!=plist);
	ListNode* tail = plist->prev;
	ListNode* tailprev = tail->prev;
	free(tail);
	plist->prev = tailprev;
	tailprev->next = plist;
}
void ListPushFront(ListNode* plist, LTDataType x)
{
	assert(plist);
	ListNode* newnode = ListCreate(x);
	ListNode* first = plist->next;
	newnode->next = first;
	first->prev = newnode;
	plist->next = newnode;
	newnode->prev = plist;
}
void ListPopFront(ListNode* plist)
{
	assert(plist);
	assert(plist->next != plist);
	ListNode* first = plist->next;
	ListNode* newfirst = first->next;
	free(first);
	plist->next = newfirst;
	newfirst->prev = plist;

}
ListNode* ListFind(ListNode* plist, LTDataType x)
{
	assert(plist);
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;

}
void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = ListCreate(x);
	ListNode* posfront = pos->prev;
	posfront->next = newnode;
	newnode->prev = posfront;
	newnode->next = pos;
	pos->prev = newnode;

}
void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* posfront = pos->prev;
	ListNode* posbehind = pos->next;
	free(pos);
	posfront->next = posbehind;
	posbehind->prev = posfront;
}
void ListDestory(ListNode* plist)
{
	assert(plist);
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(plist);
}